<template>
  <div class="user-profile-container">
    <el-card class="profile-card" shadow="hover">
      <el-row :gutter="40" justify="center">
        <!-- 左侧信息展示 -->
        <el-col :span="12" class="info-panel">
          <div class="user-info-display">
            <div class="avatar-wrapper" @click="selectImage">
              <el-avatar :src="userInfo.avatar" :size="140" class="avatar" />
              <div class="avatar-mask">
                <el-icon :size="30">
                  <Camera />
                </el-icon>
              </div>
            </div>
            <h2 class="name">{{ userInfo.userName }}</h2>
            <el-descriptions :column="1" class="info-list" border>
              <el-descriptions-item label="编号">
                <span class="desc-value">{{ userInfo.userId }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="登录账号">
                <span class="desc-value">{{ userInfo.loginName }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="电话">
                <span class="desc-value">{{ userInfo.phoneNumber }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="邮箱">
                <span class="desc-value">{{ userInfo.email }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="性别">
                <span class="desc-value">{{ getSexLabel(userInfo.sex) }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">
                <span class="desc-value">{{ userInfo.createTime }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="更新时间">
                <span class="desc-value">{{ userInfo.updateTime }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="个人介绍">
                <!-- <el-input v-model="userInfo.remark" type="textarea" class="custom-textarea"
                  :autosize="{ minRows: 4, maxRows: 18 }" disabled /> -->

                <el-text class="mx-1">{{ userInfo.remark }}</el-text>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-col>

        <!-- 右侧编辑表单（Tabs 切换个人信息 & 修改密码） -->
        <el-col :span="12" class="edit-panel">
          <el-tabs v-model="activeTab" type="card" class="edit-tabs">
            <el-tab-pane label="个人信息" name="info">
              <el-form :model="editInfo" :rules="infoRules" ref="infoForm" label-width="100px" label-position="left">
                <el-form-item label="昵称：" prop="userName">
                  <el-input v-model="editInfo.userName" size="large" placeholder="请输入昵称" class="custom-input" />
                </el-form-item>

                <el-form-item label="电话：" prop="phoneNumber">
                  <el-input v-model="editInfo.phoneNumber" size="large" placeholder="请输入手机号" class="custom-input" />
                </el-form-item>

                <el-form-item label="邮箱：" prop="email">
                  <el-input v-model="editInfo.email" size="large" placeholder="请输入邮箱" class="custom-input" />
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="editInfo.sex" size="large">
                    <el-radio-button value="0">男</el-radio-button>
                    <el-radio-button value="1">女</el-radio-button>
                    <el-radio-button value="2">保密</el-radio-button>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label="个人介绍">
                  <el-input v-model="editInfo.remark" type="textarea" class="custom-textarea"
                    :autosize="{ minRows: 4, maxRows: 18 }" placeholder="请输入个人介绍" />
                </el-form-item>


                <el-form-item class="action-buttons">
                  <el-button type="primary" size="large" @click="submitInfo" class="submit-btn">保存修改</el-button>
                  <el-button size="large" @click="resetInfo" class="reset-btn">重置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <el-tab-pane label="修改密码" name="password">
              <el-form :model="passwordInfo" :rules="passwordRules" ref="passwordForm" label-width="100px"
                label-position="left">
                <el-form-item label="新密码：" prop="password">
                  <el-input v-model="passwordInfo.password" type="password" size="large" placeholder="请输入新密码"
                    show-password class="custom-input" />
                </el-form-item>

                <el-form-item label="确认密码：" prop="confirmPassword">
                  <el-input v-model="passwordInfo.confirmPassword" type="password" size="large" placeholder="请再次输入新密码"
                    show-password class="custom-input" />
                </el-form-item>

                <el-form-item class="action-buttons">
                  <el-button type="primary" size="large" @click="submitPassword" class="submit-btn">修改密码</el-button>
                  <el-button size="large" @click="resetPassword" class="reset-btn">重置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-card>

    <input type="file" ref="fileInput" accept=".jpg,.jpeg,.png,.gif,.bmp,.webp" @change="uploadImage"
      class="file-input" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Camera } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import { updateUser, updatePassword } from '@/api/user'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
interface UserInfo {
  userId: number
  loginName: string
  userName: string
  email: string
  phoneNumber: string
  sex: string
  avatar: string
  createTime: string
  updateTime: string
  remark?: string
}

const userInfo = reactive<UserInfo>({
  userId: 0,
  loginName: '',
  userName: '',
  email: '',
  phoneNumber: '',
  sex: '2',
  avatar: '',
  createTime: '',
  updateTime: '',
  remark: ''
})


onMounted(() => {
  const storedUser = userStore.getCookieItem('userInfo')
  if (storedUser) {
    Object.assign(userInfo, storedUser)
    Object.assign(editInfo, storedUser)
  } else {
    console.warn('未找到用户信息，请重新登录')
  }
})


// 个人信息编辑数据
const editInfo = reactive({ ...userInfo })
const infoForm = ref()
const fileInput = ref<HTMLInputElement>()

// 密码修改数据
const passwordInfo = reactive({
  password: '',
  confirmPassword: ''
})
const passwordForm = ref()

const activeTab = ref('info')

const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp']

const getSexLabel = (val: string): string => ({ '0': '男', '1': '女', '2': '未知' }[val] || '未知')

const selectImage = () => fileInput.value?.click()

const uploadImage = async (e: Event) => {
  const files = (e.target as HTMLInputElement).files
  if (!files?.length) return

  const file = files[0]

  if (!allowedTypes.includes(file.type)) {
    ElMessage.warning('仅支持 jpg/jpeg/png/gif/bmp/webp 格式的图片')
    return
  }

  const maxSizeMB = 2
  if (file.size / 1024 / 1024 > maxSizeMB) {
    ElMessage.warning(`图片大小不能超过 ${maxSizeMB}MB`)
    return
  }

  try {
    const objectUrl = URL.createObjectURL(file)
    userInfo.avatar = objectUrl
    editInfo.avatar = objectUrl
    console.log('[模拟上传] 新头像 URL:', file)
  } catch {
    ElMessage.error('头像上传失败')
  }
}

// 个人信息验证规则
const infoRules = {
  userName: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  phoneNumber: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确手机号', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确邮箱', trigger: 'blur' }]
}

// 密码修改验证规则
const passwordRules = {
  password: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
  confirmPassword: [
    {
      validator: (_rule: any, value: string, callback: (error?: Error) => void) => {
        if (passwordInfo.password && value !== passwordInfo.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 保存个人信息
const submitInfo = async () => {
  infoForm.value.validate(async (valid: boolean) => {
    if (!valid) return

    const changed: Record<string, any> = { userId: userInfo.userId }
    const compareKeys = ['userName', 'phoneNumber', 'email', 'sex', 'avatar', 'remark']
    compareKeys.forEach(key => {
      if (editInfo[key] !== userInfo[key]) {
        changed[key] = editInfo[key]
      }
    })

    if (Object.keys(changed).length <= 1) {
      ElMessage.warning('未修改任何信息')
      return
    }

    try {
      await ElMessageBox.confirm('确认要保存这些修改吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
      const updateUserinfo = await updateUser(changed);
      if (updateUserinfo.code !== 200) {
        ElMessage.error('用户信息更新失败，请稍后再试')
        return
      }
      Object.assign(userInfo, editInfo)
      ElMessage.success('用户信息更新成功')
    } catch {
      // 取消操作
    }
  })
}

const resetInfo = () => {
  Object.assign(editInfo, userInfo)
}

// 修改密码提交
const submitPassword = () => {
  passwordForm.value.validate(async (valid: boolean) => {
    if (!valid) return

    try {
      await ElMessageBox.confirm('确认要修改密码吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })

      // 模拟请求提交密码修改
      const params = {
        userId: userInfo.userId,
        password: passwordInfo.password
      }
      const response = await updatePassword(params);
      if (response.code !== 200) {
        ElMessage.error('密码修改失败，请稍后再试')
        return
      }
      // 密码修改成功后逻辑，销毁token，退出登录
      ElMessage.success('密码修改成功，请重新登录')
      // 这里模拟登出，可以调用退出登录API、清理token等
      userStore.logout()
      router.push(`/login?redirect=${route.fullPath}`)
    } catch {
      // 取消操作
      ElMessage.error('密码修改失败，请稍后再试')
    }
  })
}

const resetPassword = () => {
  passwordInfo.password = ''
  passwordInfo.confirmPassword = ''
}
</script>

<style scoped lang="scss">
.user-profile-container {
  padding: 30px;
  background: #f5f7fa;
  min-height: 100vh;

  .profile-card {
    max-width: 1200px;
    margin: 20px auto;
    border-radius: 15px;
    overflow: hidden;
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);

    :deep(.el-card__body) {
      padding: 40px;
    }
  }

  .info-panel {
    padding-right: 40px;
    border-right: 1px solid #ebeef5;
  }

  .edit-panel {
    padding-left: 40px;

    .edit-tabs {
      min-height: 400px;
    }
  }

  .user-info-display {
    text-align: center;

    .avatar-wrapper {
      position: relative;
      display: inline-block;
      margin-bottom: 25px;
      cursor: pointer;
      transition: transform 0.3s;

      &:hover {
        transform: scale(1.05);

        .avatar-mask {
          opacity: 1;
        }
      }

      .avatar {
        border: 4px solid #fff;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }

      .avatar-mask {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        border-radius: 50%;
        background: rgba(0, 0, 0, 0.4);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        opacity: 0;
        transition: opacity 0.3s;
      }
    }

    .name {
      font-size: 24px;
      color: #303133;
      margin: 20px 0;
      font-weight: 600;
    }

    .info-list {
      margin-top: 25px;
      border-radius: 10px;
      overflow: hidden;

      :deep(.el-descriptions__label) {
        width: 100px;
        font-size: 14px;
        color: #606266;
        background-color: #f0f2f5;
        padding: 12px;
      }

      :deep(.el-descriptions__content) {
        font-size: 15px;
        padding: 12px;
        background-color: #ffffff;
      }

      :deep(.el-descriptions__item:nth-child(even) .el-descriptions__content) {
        background-color: #fafafa;
      }
    }
  }

  .custom-input {
    :deep(.el-input__inner) {
      height: 48px;
      line-height: 48px;
      font-size: 15px;
      border-radius: 8px;
      padding: 0 15px;
    }
  }

  .action-buttons {
    margin-top: 35px;
    display: flex;
    gap: 20px;

    .submit-btn {
      width: 160px;
      font-size: 16px;
      border-radius: 8px;
    }

    .reset-btn {
      width: 160px;
      font-size: 16px;
      border: 1px solid #dcdfe6;
      color: #606266;

      &:hover {
        border-color: #409eff;
        color: #409eff;
      }
    }
  }
}

.file-input {
  display: none;
}

.custom-textarea {
  :deep(.el-textarea__inner) {
    font-size: 15px;
    border-radius: 8px;
    padding: 10px 15px;
    line-height: 1.5;
  }
}
</style>
